-module(element_cbrowser).
-compile(export_all).

-include_lib("nitrogen/include/wf.inc").
-include("elements.hrl").

help( 0 ) ->
    [group0];
help( N ) ->
    [ list_to_atom("dir" ++ integer_to_list(N)) | help(N-1)].

make_tags( X ) ->
    help(length(X)).


render(ControlID, R) -> 
%    MCodes = cbrowser:get_code( R#cbrowser.member_id ),
    ButtonID = ControlID,

    EvR = R#cbrowser.callback,
    Delegate = get_delegate( EvR ),
    Postback = get_postback( EvR ),

    MCodes = case R#cbrowser.member_id of
		 undefined -> [];
		 MID -> cbrowser:get_code( MID )
	     end,
    
    %    MCodes = [ {"dir1", dir1, [1, 2, 3]}, {"dir2", dir2, [4, 5, 6]},  {"dir3", dir3, [7, 8, 9]} ],
    hglobals:vput( functions:id(), element_cbrowser_dirs, MCodes ),

    {CBrowser, _} = lists:foldl(
		 fun( {DirName, TagName, Items}, {Acc, LoopCounts} ) ->

			 Nitrogenized = lists:foldl(
					  fun( Item, NAcc ) ->
						 % NAcc ++ [ #sortitem{ tag=Item, body = "Item"} ]
						NAcc ++ [ #sortitem{ tag=Item, body = cbrowser:id_to_name(Item)} ]
					  end,
					  [],
					  Items ),

			 
			 {Acc ++ [#p{}, #label{text=DirName},
				  #sortblock { 
						class=R#cbrowser.class, 
						style="padding: 10px; background-color: #eee;" ,
						group= list_to_atom("group" ++ integer_to_list(LoopCounts)) ,
						connect_with_groups=all, %get_all_groups(MCodes),
						tag=TagName, 
						items=Nitrogenized,
						delegate=?MODULE }
				 ]
			  , LoopCounts + 1}
		 end,
		      {[], 0},
		      MCodes),
    
    Container = #panel { body = CBrowser ++ [#button{ id=ButtonID, text="Enregister"}]},
    
    wf:wire(ButtonID, #event{delegate=?MODULE, type=click, postback={save_layout, R#cbrowser.member_id} }),
    wf:wire(ButtonID, #event{delegate=?MODULE, type=click, postback={pass, Delegate, Postback} }),
			      
    element_panel:render(wf:temp_id(), Container).

sort_event(Tag, Items) -> 
    MCodes = hglobals:vget( functions:id(), element_cbrowser_dirs ),

    hglobals:vput(functions:id(), element_cbrowser_dirs, 
		  lists:map(
		    fun ( {DName, ElemTag, _Codes} ) when ElemTag == Tag ->
			    {DName, ElemTag, Items};
			( {DName, ElemTag, Codes} ) ->
			    {DName, ElemTag, Codes}
		    end,
		    MCodes)),
    
    
    io:format("~p~n", [hglobals:vget( functions:id(), element_cbrowser_dirs )] ),
    ok.

event( {save_layout, MID} ) ->
    cbrowser:set_codes( MID, hglobals:vget( functions:id(), element_cbrowser_dirs ) );
event( {pass, D, P} ) ->
    D:event( {P, hglobals:vget( functions:id(), element_cbrowser_dirs )}).
